from DBaseUtil import DBase
import Common

class UsersDB:
    
    Users_TABLE = "users"
    
    User_FIELD = "user"
    Item_FIELD = "item"
    
    def __init__(self, user):
        self.user = user
        self.db = DBase(user+".db", self.scriptCreateUsers())
    
    def GetLastRequestedItem(self, user):
        '''
        Return None if no request has been made before
        '''
        self.db.cursor.execute("SELECT "+ UsersDB.Item_FIELD + " FROM "+UsersDB.Users_TABLE + " \
        WHERE " + UsersDB.User_FIELD + "=?",[user])
        self.db.row = self.db.cursor.fetchone()
        
        if self.db.row is None:
            return None
                
        lastItem = self.db.row[UsersDB.Item_FIELD]
        return lastItem
    
    def SetLastRequestedItem(self, user, item):
        if self.db.UserExists(UsersDB.Users_TABLE, UsersDB.User_FIELD, user) is False:
            self.db.cursor.execute("INSERT INTO " + UsersDB.Users_TABLE + "\
            (" + UsersDB.User_FIELD + ", " + UsersDB.Item_FIELD +") \
            VALUES (?, ?)", [user, item])
        else:
            # update tableName set item = newItem where user = userName
            self.db.cursor.execute("UPDATE " + UsersDB.Users_TABLE + " SET \
            " + UsersDB.Item_FIELD + " = ? WHERE " + UsersDB.User_FIELD + " = ?", [item, user])
    
    
    def GetAdPlaylist(self, user):
        '''
        Create a PlaylistHelper from a m3u8 file on disk
        '''
        pass
    
    def scriptCreateUsers(self):
        return "CREATE TABLE IF NOT EXISTS " + UsersDB.Users_TABLE + " ( \
        " + UsersDB.User_FIELD + " TEXT PRIMARY KEY, \
        " + UsersDB.Item_FIELD + " TEXT NOT NULL);"
        
    def DeleteDB(self):
        Common.getLogger.logthis("Deleting data from " + self.user + ".db")
        self.db.cursor.execute("DELETE FROM " + UsersDB.Users_TABLE + " WHERE " + UsersDB.User_FIELD + " = '%s'" % self.user)
#        Common.DeleteFile(self.db.GetFileName(), True)
        
